var daysStorage = null;

function updateTips(t) {
	var tips = $( ".validateTips" );
	tips.text(t).addClass("ui-state-error");
	setTimeout(function() {
		tips.removeClass("ui-state-error");
	}, 3000);
}

function checkLength(o, n, min, max) {
	if (o.val().length > max || o.val().length < min) {
		o.addClass("ui-state-error");
		updateTips("Texto de " + n + " deve conter entre " + min + " e " + max + " caracteres.");
		return false;
	} else {
		return true;
	}
}

function checkRegexp(o, regexp, n) {
	if (!(regexp.test(o.val()))) {
		o.addClass("ui-state-error");
		updateTips(n);
		return false;
	} else {
		return true;
	}
}

function setupMenu(selector) {
    var menu = $(selector);
    
    menu.find('ul').each(function() {
        var ul = $(this),
            pointer = $('<span class="nav-pointer">&raquo;</span>'),
            arrow = $('<span class="pointer"></span>');
        
        arrow.insertAfter(ul);
        ul.parent().find('a:first').append(pointer);
    });
}

function setupSchedule(startHour, scheduleURI, readonly) {
	setHeaders(scheduleURI);
	$.ajax({
		url: scheduleURI + '/timebreaks.action',
		type: 'POST',
		dataType: 'json',
		success: function(response) {
			for (var i = 0; i < response.length; i++) {
				for (var j = 0; j < 4; j++) {
					if (response[i][j] == 1) {
						$("<div />")
							.addClass("nonBusinessHour")
							.css("left", (j * 45) + "px")
							.css("top", (i * 23 + 1) + "px")
							.appendTo($(".openClinicCalendarDataHolder").eq(0));
					}
				}
			}
			
			var source = $(".openClinicCalendarDataHolder").eq(0);
			for (var i = 1; i < 5; i++) {
				$("div", source).each(function() {
					var node = $(this);
					node
						.clone()
						.css("left", node.css("left") + (i * 180))
						.appendTo($(".openClinicCalendarDataHolder").eq(i));
				});
			}
			
			if (!readonly) {
				$(".openClinicCalendarData").click(function(e){
					var parentOffset = $(this).parent().offset();
					var x = e.pageX - parentOffset.left - 41; 
					var y = e.pageY - parentOffset.top - 22;
					
					if (x < 0 || y < 0) {
						return
					}

					var hours = Math.floor(y / 23) + startHour;
					var minutesQuadrant = Math.floor(x / 45);
					var day = Math.floor(minutesQuadrant / 4);
					var minutes = (minutesQuadrant - day * 4) * 15;
					
					$("#normal").attr('checked', true);
					$("#appointmentDate").val(daysStorage[day].date + " " + (hours < 10 ? "0" + hours : hours) + ":" + (minutes == 0 ? "00" : minutes));
					$("#cancelAppointmentAction").hide();
					$("#saveAppointmentAction").show();
					
					with ($("#name")) {
						if (val() == "") {
							focus();
						}
					}
				});
			}
			
			$(".nonBusinessHour").click(function(e){				
				return false;
			});
		}
	});
	
	$("#specialtyId").change(function() {
		var professional = $("#professionalId");
		professional
			.find('option')
			.remove()
			.end();
		$.ajax({
			url: scheduleURI + '/../healthProfessional/findBySpecialty.action',
			dataType: 'json',
			data: {
				specialtyId: $("#specialtyId").val()
			},
			type: 'POST',
			success: function(response) {
				$.each(response, function(index, entry) {   
					professional
						.append($('<option>', { value : entry.value })
						.text(entry.key));
				});
				
				$("#professionalId").trigger("change");
			}
		});
	});
	
	$("#professionalId").change(function() {
		$(".busy").remove();
		$.ajax({
			url: scheduleURI + '/appointments.action',
			dataType: 'json',
			data: {
				startDate: daysStorage[0].date,
				specialtyId: $("#specialtyId").val(),
				professionalId: $(this).val()
			},
			type: 'POST',
			success: function(response) {
				for (var h = 0; h < response.length; h++) {
					for (var i = 0; i < response[h].length; i++) {
						for (var j = 0; j < 4; j++) {
							if (response[h][i][j] != 0) {
								$("<div />")
									.attr("id", "appointment" + response[h][i][j])
									.addClass("busy")
									.css("left", (j * 45 + 1) + "px")
									.css("top", (i * 23 + 1) + "px")
									.text(((i + startHour) < 10 ? "0" + (i + startHour) : i + startHour) + ":" + (j == 0 ? "00" : j * 15))
									.appendTo($(".openClinicCalendarDataHolder").eq(h));
							}
						}
					}
				}
				
				$(".busy").click(function(e) {				
					e.preventDefault();
					return onBusyClick(readonly, $(this).attr("id").substring(11));
				}).mouseenter(function(e) {
					e.stopPropagation();
				});
			}
		});
	});
	
	var schedulePopover = 
		$("<div/>")
			.addClass("schedule-popover popover")
			.appendTo(".openClinicCalendarContainer");
	var scheduleInnerPopover = $("<div/>")
		.addClass("popover-inner")
		.text("09:15")
		.appendTo(schedulePopover);
	$("<div/>")
		.addClass("popover-pointer")
		.appendTo(schedulePopover);
	
	$(".openClinicCalendarData").hover(
			function() {
				schedulePopover.show();
			},
			function() {
				schedulePopover.hide();
			}
	);
	
	$(".openClinicCalendarData").mousemove(function (e) {
		var parentOffset = $(this).parent().offset();
		var x = e.pageX - parentOffset.left - 41; 
		var y = e.pageY - parentOffset.top - 22;
		
		if (x < 0 || y < 0) {
			return
		}

		var hoursQuadrant = Math.floor(y / 23);
		var minutesQuadrant = Math.floor(x / 45);
		var day = Math.floor(minutesQuadrant / 4);
		var hours = hoursQuadrant + startHour;
		var minutes = (minutesQuadrant - day * 4) * 15;
		var posX = (minutesQuadrant * 45) + 41;
		var posY = hoursQuadrant * 23 - 8;
		
		if (schedulePopover.css("left") != posX && schedulePopover.css("top") != posY) {
			schedulePopover.css({ "left": posX + "px", "top": posY + "px" });
		} else { 
			if (schedulePopover.css("left") != posX) {
				schedulePopover.css("left", posX + "px");
			}
			if (schedulePopover.css("top") != posY) {
				schedulePopover.css("top", posY + "px");
			}
		}
		
		scheduleInnerPopover.text((hours < 10 ? "0" + hours : hours) + ":" + (minutes == 0 ? "00" : minutes));
	});
	
	$("#specialtyId").trigger("change");
}

function setHeaders(scheduleURI, date) {
	$.ajax({
		url: scheduleURI + '/headers.action',
		type: 'POST',
		dataType: 'json',
		data: {
			startDate: date
		},
		success: function(response) {
			daysStorage = response;
			for (var i = 0; i < response.length; i++) {
				$(".openClinicHeaderCell").eq(i).text(response[i].display);
			}
			
			if (date != null) {
				$("#professionalId").trigger("change");
			}
		}
	});
}

function onBusyClick(readonly, appointmentId) {
	if (readonly) {
		return false;
	}
	
	$("#appointmentId").val(appointmentId);
	
	$.ajax({
		url: 'appointment/load.action',
		dataType: 'json',
		data: {
			"appointmentId": appointmentId
		},
		type: 'POST',
		success: function(response) {
			$("#appointmentDate").val(new Date(response.startDate).format("dd/MM/yyyy HH:mm"));
			$("#customerId").val(response.customer.userId);
			$("#name").val(response.customer.name);
			
			loadHistory();
		}
	});
	
	$("#saveAppointmentAction").hide();
	$("#cancelAppointmentAction").show();
	
	return false;
}

function isEmpty(object) {
	var empty = true;

	for(var f in object) {
		empty = false;
		break;
	}
	
	return empty;
}

function mondayOnly(date) {
    if (date.getDay() === 1) {
        return [true, ""];
    } else {
        return [false, ""];
    }
}

$(document).ready(function() {
	setupMenu('#header .nav-h:first');
});